<template>
  <div>
    <el-container>
      <!-- badges -->
      <el-header>
        <div class="badges">
          <el-radio-group
            @change="handleBadge"
            v-model="badgeRadio"
            size="small"
          >
            <el-badge :value="badge.all" class="item" type="primary">
              <el-radio-button label="1">全部商品</el-radio-button>
            </el-badge>
            <el-badge :value="badge.sale" class="item" type="success">
              <el-radio-button label="2">已上架</el-radio-button>
            </el-badge>
            <el-badge :value="badge.sold" class="item" type="danger">
              <el-radio-button label="3">未上架</el-radio-button>
            </el-badge>
            <el-badge :value="badge.audit" class="item" type="warning">
              <el-radio-button label="4">待审核</el-radio-button>
            </el-badge>
            <el-badge :value="badge.inReview" class="item">
              <el-radio-button label="5">未通过</el-radio-button>
            </el-badge>
          </el-radio-group>
        </div>
      </el-header>
      <!-- 查询 -->
      <el-main>
        <div class="module-search">
          <div class="row-1">
            <div class="title">查询条件</div>
            <!-- <el-button @click="onSubmit">查询结果</el-button> -->
            <div style="float:right;">
              <el-button
                @click="dialogSearch = true"
                icon="el-icon-search"
                size="medium"
                >高级检索</el-button
              >
            </div>
          </div>
          <div class="row-2">
            <el-form :inline="true" class="demo-form-inline">
              <el-form-item label="输入搜索:">
                <el-input
                  @keyup.enter.native="initTable"
                  v-model="search.nameOrEncode"
                  placeholder="商品名称/商品货号"
                ></el-input>
              </el-form-item>
              <el-form-item label="商品分类">
                <el-cascader
                  ref="myCascader"
                  v-model="search.category"
                  @change="handleCascader('myCascader')"
                  :props="cascader"
                  popper-class="category"
                  expand-trigger="hover"
                  placeholder="请选择商品分类"
                  clearable
                ></el-cascader>
              </el-form-item>
              <el-form-item label="商品品牌">
                <el-select
                  v-model="search.brand"
                  placeholder="请选择商品品牌"
                  clearable
                >
                  <el-option
                    v-for="(item, index) in brands"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-main>
      <el-footer>
        <el-container class="parent-body">
          <!-- <el-main> -->
          <div class="module-table">
            <div class="table-header">
              <span> <i class="el-icon-s-unfold"></i> 数据列表 </span>
              <div style="float:right">
                <el-select
                  v-model="search.sort"
                  class="selection-width margin-left"
                  size="small"
                  placeholder="排列方式"
                >
                  <el-option
                    v-for="item in sortOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </div>
            </div>
            <div>
              <el-table
                border
                ref="table"
                :data="tableData"
                tooltip-effect="dark"
                style="width: 100%"
                @selection-change="handleSelectionChange"
              >
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column
                  prop="id"
                  label="编号"
                  width="120"
                ></el-table-column>
                <el-table-column prop="image" label="商品图片" width="180">
                  <!-- solt-scope=”scope” -->
                  <template scope="scope">
                    <img :src="scope.row.image.url" width="100" height="100" />
                  </template>
                </el-table-column>
                <el-table-column label="商品名称">
                  <template scope="scope">
                    <!-- <p style="text-align:left;">{{scope.row.name}}</p> -->
                    <p>{{ scope.row.name }}</p>
                    <p>品牌：{{ scope.row.brandName }}</p>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="encode"
                  label="货号"
                  width="200"
                ></el-table-column>
                <!-- <el-table-column prop="address" label="价格" width="100"></el-table-column> -->
                <el-table-column label="上架" width="100">
                  <template scope="scope">
                    <el-switch
                      @change="handleSwitch(scope.row)"
                      v-model="scope.row.marketable"
                      :active-value="true"
                      :inactive-value="false"
                      :disabled="
                        scope.row.isDelete == 1 || scope.row.status != 2
                      "
                      active-color="#13ce66"
                    ></el-switch>
                  </template>
                </el-table-column>
                <el-table-column label="SKU库存" width="100">
                  <template scope="scope">
                    <el-button
                      @click="handleSkuDialog(scope.row)"
                      type="primary"
                      icon="el-icon-edit"
                      circle
                    ></el-button>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="sale"
                  label="销量"
                  width="100"
                ></el-table-column>
                <el-table-column prop="address" label="审核状态" width="120">
                  <template scope="scope">
                    {{ scope.row.staLabel }}
                    <el-button type="text" icon="el-icon-search"
                      >审核详情</el-button
                    >
                  </template>
                </el-table-column>
                <el-table-column
                  prop="delLabel"
                  label="商品状态"
                  width="80"
                ></el-table-column>
                <el-table-column fixed="right" label="操作" width="150">
                  <template slot-scope="scope">
                    <el-button
                      class="table-button"
                      size="small"
                      @click="show(scope.row)"
                      >查看</el-button
                    >
                    <el-button
                      class="table-button"
                      size="small"
                      @click="redact(scope.row)"
                      >编辑</el-button
                    >
                    <el-button
                      class="table-button"
                      size="small"
                      @click="lookLog"
                      >日志</el-button
                    >
                    <el-button
                      :disabled="scope.row.isDelete == 1"
                      @click="handleDel(scope.row.id)"
                      class="table-button"
                      size="small"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
          <!-- </el-main> -->
          <el-footer class="module-footer">
            <div class="batch">
              <el-button @click="toggleSelection" size="small">全选</el-button>
              <el-select
                v-model="batchType"
                placeholder="批量操作"
                size="small"
                class="selection-width margin-left"
                clearable
              >
                <el-option label="删除选中" value="0"></el-option>
                <el-option label="还原删除" value="1"></el-option>
                <el-option label="商品上架" value="2"></el-option>
                <el-option label="商品下架" value="3"></el-option>
                <!-- <el-option label="设为推荐" value="4"></el-option>
                <el-option label="取消推荐" value="5"></el-option>
                <el-option label="设为新品" value="6"></el-option>
                <el-option label="取消新品" value="7"></el-option>
                <el-option label="转移到分类" value="8"></el-option>
                <el-option label="移入回收站" value="9"></el-option>-->
              </el-select>
              <el-button @click="handleBatch" class="margin-left" size="small"
                >确定</el-button
              >
            </div>
            <div class="pagination">
              <el-pagination
                @current-change="pageCurrentChange"
                @size-change="pageSizeChange"
                :current-page="page.pageNum"
                :page-sizes="page.pageSizes"
                :page-size="page.pageSize"
                :pager-count="11"
                layout="total, sizes, prev, pager, next, jumper"
                :total="page.total"
              ></el-pagination>
            </div>
          </el-footer>
        </el-container>
      </el-footer>

      <div>
        <!-- 高级检索对话框 -->
        <el-dialog
          title="高级检索"
          :visible.sync="dialogSearch"
          class="search-form"
          width="30%"
        >
          <el-form
            ref="searchForm"
            :inline="true"
            :model="searchForm"
            label-position="top"
          >
            <el-form-item label="商品分类">
              <el-cascader
                ref="formCascader"
                v-model="searchForm.category"
                @change="handleCascader('formCascader')"
                :props="cascader"
                popper-class="category"
                expand-trigger="hover"
                placeholder="请选择商品分类"
                clearable
              ></el-cascader>
            </el-form-item>
            <el-form-item label="商品品牌">
              <el-select
                v-model="searchForm.brand"
                placeholder="请选择商品品牌"
                clearable
              >
                <el-option
                  v-for="(item, index) in brands"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商品状态">
              <el-select
                v-model="searchForm.available"
                placeholder="全部"
                clearable
              >
                <el-option label="正常" value="0"></el-option>
                <el-option label="已删" value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="审核状态">
              <el-select
                v-model="searchForm.audit"
                placeholder="全部"
                clearable
              >
                <el-option label="未审核" value="0"></el-option>
                <el-option label="未通过" value="1"></el-option>
                <el-option label="已审核" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="上下架状态">
              <el-select v-model="searchForm.sold" placeholder="全部" clearable>
                <el-option label="已上架" value="1"></el-option>
                <el-option label="未上架" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="输入搜索">
              <el-input
                v-model="searchForm.nameOrEncode"
                placeholder="商品名称/商品货号"
              ></el-input>
            </el-form-item>
          </el-form>
          <span  slot="footer" class="dialog-footer">
            <el-button @click="resetForm('searchForm')">重置</el-button>
            <el-button type="primary" @click="confirmSearch"
              >开始检索</el-button
            >
          </span>
        </el-dialog>
        <!-- 编辑商品SKU信息对话框 -->
        <el-dialog
          title="编辑货品信息"
          :visible.sync="skuDialog.show"
          width="50%"
        >
          <div>
            <el-form label-width="300px">
              <el-form-item :label="'商品货号：' + skuDialog.spuEncode">
                <div style="display:inline-block">
                  <el-input
                    v-model="skuDialog.skuEncode"
                    placeholder="请输入SKU编号"
                    class="input-with-select"
                  >
                    <el-button
                      @click="searchSkuList"
                      slot="append"
                      icon="el-icon-search"
                    ></el-button>
                  </el-input>
                </div>
              </el-form-item>
            </el-form>
            <div>
              <el-table
                :data="skuDialog.tableData"
                border
                height="250"
                style="width: 100%"
                :header-cell-style="headerCellStyle"
              >
                <el-table-column label="SKU编号" align="center">
                  <template scope="scope">
                    <el-input
                      @blur="updateSku(scope.row)"
                      v-model="scope.row.encode"
                    ></el-input>
                  </template>
                </el-table-column>
                <!-- v-for="(item, index) in skuDialog.tableData.specs" -->
                <el-table-column
                  v-for="(item, index) in skuDialog.tableColumn"
                  :key="index"
                  :prop="item.prop"
                  :label="item.label"
                  align="center"
                ></el-table-column>
                <el-table-column label="销售价格 (元)" align="center">
                  <template scope="scope">
                    <el-input
                      @blur="updateSku(scope.row)"
                      v-model.trim="scope.row.price"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="商品库存" align="center">
                  <template scope="scope">
                    <el-input
                      @blur="updateSku(scope.row)"
                      v-model.number="scope.row.repertory"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="库存预警值" align="center">
                  <template scope="scope">
                    <el-input
                      @blur="updateSku(scope.row)"
                      v-model.number="scope.row.warning"
                    ></el-input>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-dialog>
      </div>
    </el-container>
  </div>
</template>

<script>
import classifyApi from "@/api/goods/classify";
import brandApi from "@/api/goods/brand";
import skuApi from "@/api/goods/sku";
import spuApi from "@/api/goods/spu";

export default {
  data() {
    return {
      brands: [],
      categories: [],
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      badgeRadio: 1,
      badge: {
        all: 0,
        sale: 0,
        sold: 0,
        audit: 0,
        inReview: 0
      },
      dialogSearch: false,
      search: {
        sort: null,
        nameOrEncode: "",
        brand: null,
        category: [],
        audit: null,
        available: null,
        sold: null
      },
      searchForm: {
        sort: null,
        nameOrEncode: "",
        brand: null,
        category: [],
        audit: null,
        available: null,
        sold: null
      },
      cascader: {
        checkStrictly: true,
        lazy: true,
        lazyLoad(node, resolve) {
          // const { level } = node; // = node.level
          const { value } = node;
          let parentId = value;
          if (parentId == undefined) {
            parentId = 0;
          }
          setTimeout(() => {
            classifyApi.getListById(parentId).then(result => {
              if (result.data.data.length > 0) {
                const nodes = Array.from(result.data.data).map(item => ({
                  value: item.categoryId,
                  label: item.categoryName
                  // 是否为叶子节点的标志位 (默认字段为leaf，可通过props.leaf修改)
                  // leaf: level > item.categoryLevel
                }));
                // 通过调用resolve将子节点数据返回，通知组件数据加载完成
                resolve(nodes);
              } else {
                resolve();
              }
            });
          }, 1000);
        }
      },
      sortOptions: [
        {
          label: "商品编号",
          value: 0
        },
        {
          label: "商品名称",
          value: 1
        },
        {
          label: "商品货号",
          value: 2
        },
        {
          label: "上架状态",
          value: 3
        },
        {
          label: "销量",
          value: 4
        },
        {
          label: "审核状态",
          value: 5
        },
        {
          label: "商品状态",
          value: 6
        }
      ],
      tableData: [],
      batchType: null,
      batchTarget: [],
      skuDialog: {
        show: false,
        tableColumn: [],
        tableData: [],
        spuEncode: "",
        skuEncode: "",
        row: {
          enocde: "",
          price: null,
          repertory: null,
          warning: null
        }
      }
    };
  },
  methods: {
    // 初始化操作
    initData() {
      brandApi.listBaseInfo().then(result => {
        this.brands = result.data.data;
      });
      spuApi.count().then(result => {
        this.badge.all = result.data.data.total;
        this.badge.sale = result.data.data.sale;
        this.badge.sold = result.data.data.sold;
        this.badge.audit = result.data.data.audit;
        this.badge.inReview = result.data.data.inReview;
      });
      this.initTable();
    },
    initTable() {
      let match = {
        sort: this.search.sort - 0,
        nameOrEncode: this.search.nameOrEncode,
        brand: this.search.brand,
        category: this.arrayToString(this.search.category),
        audit: this.search.audit,
        available: this.search.available,
        sold: this.search.sold,
        pageNum: this.page.pageNum,
        pageSize: this.page.pageSize
      };
      spuApi.pageMatchList(match).then(result => {
        this.tableData = result.data.data.list;
        this.tableData.forEach((item, index) => {
          let img = {
            url: null,
            name: "",
            size: null
          };
          if (item.image) {
            img = JSON.parse(item.image);
          }
          this.tableData[index].image = img;
        });
        this.page.total = result.data.data.total;
      });
    },
    // 商品 分类查询操作
    handleBadge() {
      this.search = {
        sort: null,
        nameOrEncode: "",
        brand: null,
        category: [],
        audit: null,
        available: null,
        sold: null
      };
      switch (this.badgeRadio - 0) {
        case 1:
          break;
        case 2:
          this.$set(this.search, "audit", null);
          this.$set(this.search, "sold", 1);
          break;
        case 3:
          this.search.audit = null;
          this.search.sold = 0;
          break;
        case 4:
          this.search.audit = 0;
          this.search.sold = null;
          break;
        case 5:
          this.search.audit = 1;
          this.search.sold = null;
          break;
        default:
          break;
      }
      // 执行条件查询
      this.initTable();
    },
    // 高级查询操作
    handleMoreSearch() {
      this.dialogSearch = true;
    },
    // 分类选择
    handleCascader(target) {
      // 目的是选择之后将下拉界面收起
      this.$refs[target].toggleDropDownVisible();
      if (target == "myCascader") {
        this.initTable();
      }
    },
    // 上下架操作
    handleSwitch(target) {
      var spu = {
        id: target.id,
        marketable: target.marketable
      };
      spuApi.updateById(spu).then(() => {
        this.initTable();
      });
    },
    // 删除操作
    handleDel(id) {
      spuApi.deleteById(id).then(() => {
        this.initTable();
      });
    },
    // SKU对话框 操作
    handleSkuDialog(target) {
      this.skuDialog.spuEncode = target.encode;
      skuApi.listById(target.id).then(result => {
        if (result.data.data) {
          this.skuDialog.tableData = result.data.data;
          this.skuDialog.tableColumn = JSON.parse(
            this.skuDialog.tableData[0].spec
          );
          this.skuDialog.tableData.forEach((item, index) => {
            let specs = JSON.parse(item.spec);
            specs.forEach($item => {
              this.$set(
                this.skuDialog.tableData[index],
                $item.prop,
                $item.value
              );
            });
          });
        }
      });
      this.skuDialog.show = true;
    },
    searchSkuList() {
      skuApi.match(this.skuDialog.skuEncode).then(result => {
        if (result.data.data) {
          this.skuDialog.tableData = result.data.data;
          this.skuDialog.tableColumn = JSON.parse(
            this.skuDialog.tableData[0].spec
          );
          this.skuDialog.tableData.forEach((item, index) => {
            let specs = JSON.parse(item.spec);
            specs.forEach($item => {
              this.$set(
                this.skuDialog.tableData[index],
                $item.prop,
                $item.value
              );
            });
          });
        }
      });
    },
    updateSku(target) {
      let sku = {
        id: target.id,
        encode: target.encode,
        price: target.price,
        repertory: target.repertory,
        warning: target.warning
      };
      skuApi.updateById(sku).then(() => {});
    },

    // 全选操作
    handleSelectionChange(val) {
      val.forEach((item, index) => {
        let target = {
          id: item.id,
          del: item.isDelete
        };
        this.batchTarget.splice(index, this.batchTarget.length - index, target);
      });
    },
    // 数据列表
    toggleSelection() {
      if (this.tableData) {
        this.tableData.forEach(() => {
          // 全选 或 反选
          // this.$refs.multipleTable.toggleRowSelection(row);
          // 全选 或 全不选
          this.$refs.table.toggleAllSelection();
        });
      } else {
        this.$refs.table.clearSelection();
      }
    },
    // 分页操作
    pageSizeChange(val) {
      this.page.pageSize = val;
      this.page.pageNum = 1;
      this.initTable();
    },
    pageCurrentChange(val) {
      this.page.pageNum = val;
      this.initTable();
    },
    // 批量操作
    handleBatch() {
      switch (this.batchType - 0) {
        case 0:
          this.batchTarget.forEach(item => {
            this.handleDel(item.id);
          });
          break;
        case 1:
          this.batchTarget.forEach(item => {
            var spu = {
              id: item.id,
              isDelete: 0
            };
            spuApi.updateById(spu).then(() => {
              this.initTable();
            });
          });
          break;
        case 2:
          this.batchTarget.forEach(item => {
            if (item.del == 0 && item.status == 2) {
              var spu = {
                id: item.id,
                marketable: true
              };
              this.handleSwitch(spu);
            }
          });
          break;
        case 3:
          this.batchTarget.forEach(item => {
            // if (item.del == 0) {
            var spu = {
              id: item.id,
              marketable: false
            };
            this.handleSwitch(spu);
            // }
          });
          break;
        default:
          break;
      }
    },

    // 搜索对话框操作
    resetForm(formName) {
      // console.log(formName);
      this.searchForm = {
        sort: null,
        nameOrEncode: "",
        brand: null,
        category: [],
        audit: null,
        available: null,
        sold: null
      };
      this.$refs[formName].resetFields();
    },
    confirmSearch() {
      this.dialogSearch = false;
      this.search = this.searchForm;
      this.initTable();
    },
    lookLog() {
      this.$router.push("/goods/log");
    },
    // 编辑
    redact(target) {
      this.$router.push({
        path: "/goods/modify",
        // name: "modify",
        query: {
          id: target.id
        }
      });
    },
    // 查看
    show(target) {
      this.$router.push({
        path: "/goods/details",
        // name: "modify",
        query: {
          id: target.id
        }
      });
    },
    headerCellStyle() {
      return "background-color: #f9fafc;";
    },
    arrayToString(arr) {
      var arrStr = "";
      arr.forEach((item, index) => {
        if (index == 0) {
          arrStr = item;
        } else {
          arrStr += ";" + item;
        }
      });
      return arrStr;
    }
  },
  watch: {
    badgeRadio() {
      // this.handleBadge();
    },
    "search.sort": function() {
      this.initTable();
    },
    "search.brand": function() {
      this.initTable();
    }
  },
  created() {
    this.initData();
  }
};
</script>
<style scoped>
.badges {
  height: 60px;
  padding: 10px;
}
.table-button {
  margin: 3px 4px;
  display: inline-block;
}
.module-search {
  border: 1px solid #e4e4e4;
}
.module-search .row-1 {
  height: 40px;
  line-height: 40px;
  padding: 10px 20px;
  border-bottom: 1px solid #e4e4e4;
  background-color: rgba(243, 243, 243, 1);
  /* box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); */
}
.module-search .row-1 .title {
  color: #666666;
  display: inline-block;
}
.module-search .row-2 {
  height: 60px;
  padding: 20px;
  /* box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); */
}
.module-table .table-header {
  border-bottom: 1px solid #e4e4e4;
  padding: 5px 20px;
  height: 50px;
  line-height: 50px;
  background-color: #f3f3f3;
  color: #666666;
  position: relative;
  text-align: left;
}
.module-footer {
  background-color: #fdfdfe;
  height: 60px;
  line-height: 60px;
  position: relative;
}
.module-footer .batch {
  position: absolute;
  left: 10px;
}
.module-footer .pagination {
  position: absolute;
  right: 10px;
  display: inline-block;
  top: 15px;
}
</style>
<style>
.item {
  margin-top: 20px;
  margin-right: 40px;
}
.el-dialog__header {
  border-bottom: 1px solid #e4e4e4;
  font-weight: bold;
  background-color: #f2f2f2;
}
.el-dialog__header .el-dialog__title {
  color: #666666;
}
.category .el-cascader-panel .el-radio {
  width: 100%;
  height: 100%;
  z-index: 10;
  position: absolute;
  top: 0px;
  right: 0px;
}
.category .el-cascader-panel .el-radio__input {
  /* margin-top: 10px;
   	margin-left: 8px; 		 */
  /* 隐藏单选框 圆点 */
  visibility: hidden;
}
.category .el-cascader-panel .el-cascader-node__postfix {
  /* 选项后面的箭头i标签 其原本样式 top:10px  */
  top: 10px;
}
.search-form .el-form--inline .el-form-item {
  width: 217px;
  margin-left: 25px;
}
</style>
